<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>系统界面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 委托商名称 -->
        <div class="form-item">
            <label class="form-label">委托商：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入委托商名称">
        </div>
        <!-- 类型选择 -->
        <div class="form-item">
            <label class="form-label">类型：</label>
            <select class="form-input form-select form-select-type" id="form-select-type">
                <option value="">全部</option>
<!--                <option value="1">启用</option>-->
<!--                <option value="0">停用</option>-->
            </select>
        </div>
        <!-- 状态选择 -->
        <div class="form-item">
            <label class="form-label">状态：</label>
            <select class="form-input form-select-status form-select">
                <option value="">全部</option>
                <option value="0">待审核</option>
                <option value="1">合作中</option>
                <option value="2">已退出</option>
            </select>
        </div>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
        <button class="btn btn-export">导出Excel</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>委托商全称</th>
            <th>委托商简称称</th>
            <th>类型</th>
            <th>联系电话</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content">
        <h3 class="modal-title">
            新增委托商
            <button class="modal-close-btn">×</button>
        </h3>

        <form class="modal-form" id="modal-form-add">
            <div class="form-item">
                <label>委托商名称：</label>
                <input type="text" id="add-customerName" required>
            </div>
            <div class="form-item">
                <label>委托商简称：</label>
                <input type="text" id="add-customerSimple" required>
            </div>
            <div class="form-item">
                <label>类型：</label>
                <select id="add-typeId" required>
                    <option value="">请选择类型</option>
                </select>
            </div>
            <div class="form-item">
                <label>联系电话：</label>
                <input type="text" id="add-telephone" required>
            </div>
            <div class="form-item">
                <label>邮箱：</label>
                <input type="email" id="add-mailbox">
            </div>
            <div class="form-item">
                <label>详细地址：</label>
                <input type="text" id="add-address">
            </div>

            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">新增</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-update">
    <div class="modal-content">
        <h3 class="modal-title">
            修改委托商
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-update">
            <div class="form-item">
                <label>委托商名称：</label>
                <input type="text" id="update-customerName" required>
            </div>
            <div class="form-item">
                <label>委托商简称：</label>
                <input type="text" id="update-customerSimple" required>
            </div>
            <div class="form-item">
                <label>联系电话：</label>
                <input type="text" id="update-telephone" required>
            </div>
            <div class="form-item">
                <label>邮箱：</label>
                <input type="email" id="update-mailbox">
            </div>
            <div class="form-item">
                <label>详细地址：</label>
                <input type="text" id="update-address">
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">保存</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-detail">
    <div class="modal-content">
        <h3 class="modal-title">
            委托商详情
            <button class="modal-close-btn">×</button>
        </h3>
        <div class="modal-body">
            <!-- 基础信息 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">基础信息</h4>
                <div class="detail-row">
                    <span class="detail-label">委托商名称：</span>
                    <span id="detail-customerName" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">委托商简称：</span>
                    <span id="detail-customerSimple" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">类型：</span>
                    <span id="detail-typeName" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">联系电话：</span>
                    <span id="detail-telephone" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">邮箱：</span>
                    <span id="detail-mailbox" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">详细地址：</span>
                    <span id="detail-address" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">状态：</span>
                    <span id="detail-status" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">创建时间：</span>
                    <span id="detail-createTime" class="detail-value"></span>
                </div>
            </div>

            <!-- 操作记录 -->
            <div class="detail-section">
                <h4 class="detail-subtitle">操作记录</h4>
                <div id="detail-operationLogs" class="detail-logs">
                    暂无数据
                </div>
            </div>
        </div>
        <div class="modal-buttons">
            <button type="button" class="btn-close">关闭</button>
        </div>
    </div>
</div>
<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')
    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');
            let status = ""
            if (item.status ===1){
                status = "合作中"
            }else if (item.status ===2){
                status = "已退出"
            }else if (item.status ===0){
                status = "待审核"
            }
            // 生成表格内容
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.customerName}</td>
                <td>${item.customerSimple || ''}</td>
                <td>${item.typeName || ''}</td>
                <td>${item.telephone || ''}</td>
                <td>${status}</td>
                <td>
                    <button class="table-detail-btn">详情</button>
                    <button class="table-disable-btn">禁用</button>
                    <button class="table-edit-btn">修改</button>
                    <!-- <button class="table-delete-btn">删除</button> -->
                </td>
            `;

            // 设置tr的data-id属性
            tr.dataset.id = item.id;

            // 绑定操作按钮事件
            const detailBtn = tr.querySelector('.table-detail-btn');
            const disableBtn = tr.querySelector('.table-disable-btn');
            const editBtn = tr.querySelector('.table-edit-btn');
            // const deleteBtn = tr.querySelector('.table-delete-btn');
            
            // 禁用/启用切换
            let state =0
            if ( item.status ===2){
                state ='启用合作'
            }else if( item.status ===1){
                state ='终止合作'
            }else {
                state ='发送审核'
            }

            disableBtn.addEventListener('click', () => disableCustomer(item.id, item.status));
            disableBtn.textContent = state;
            detailBtn.addEventListener('click', () => showCustomerDetail(item));
            editBtn.addEventListener('click', () => showUpdateModal(item.id));
            // deleteBtn.addEventListener('click', () => deleteDepartment(item.id));

            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {

        let { page, pageSize } = getPaginationParams();
        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }
        const queryParams = {
            customerName: document.querySelector('input[placeholder="请输入委托商名称"]').value,
            typeId: document.querySelector('.form-select-type').value,
            status: document.querySelector('.form-select-status').value,
            page: page,
            rows: pageSize
        };

        // try {
            const response = await fetch('http://localhost:8080/sys/customerInfo/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        }
        // catch (error) {
        //     console.error('请求失败:', error);
        //     renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        // }

    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '' // 清空文本输入
            if (input.tagName === 'SELECT') input.value = '' // 重置选择框
        });

    })
    //新增按钮相关
    // 显示弹窗
    document.querySelector('.btn-add').addEventListener('click', () => {
        document.querySelector('#modal-mask-add').style.display = 'flex';
        // 初始化类型下拉框
        initTypeSelect();
    });

    // 初始化类型下拉框
    async function initTypeSelect() {
        try {
            const response = await fetch('http://localhost:8080/sys/customerType/selectAllCustomerType', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });
            const data = await response.json();
            if (data.status === 0) {
                const select = document.getElementById('add-typeId');
                // 清空现有选项（保留第一个空选项）
                while (select.options.length > 1) {
                    select.remove(1);
                }
                // 添加新选项
                data.data.forEach(item => {
                    const option = document.createElement('option');
                    option.value = item.id;
                    option.textContent = item.type_name;
                    select.appendChild(option);
                });
            }
        } catch (err) {
            console.error('加载类型失败:', err);
            alert('加载类型失败');
        }
    }

    // 新增表单提交处理
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = {
            customerName: document.getElementById('add-customerName').value,
            customerSimple: document.getElementById('add-customerSimple').value,
            typeId: document.getElementById('add-typeId').value,
            telephone: document.getElementById('add-telephone').value,
            mailbox: document.getElementById('add-mailbox').value,
            address: document.getElementById('add-address').value,
            status: 0 // 默认状态为待审核
        };

        try {
            const response = await fetch('http://localhost:8080/sys/customerInfo/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });
            const data = await response.json();
            if (data.status === 0) {
                alert('新增成功');
                document.querySelector('#modal-mask-add').style.display = 'none';
                // 清空表单
                document.querySelector('#modal-form-add').reset();
                // 刷新表格数据
                fetchData('query');
            } else {
                alert('新增失败：' + (data.message || '未知错误'));
            }
        } catch (err) {
            console.error('提交失败:', err);
            alert('提交失败：' + err.message);
        }
    });

    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    // 表单提交处理
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault()

        const formData = {
            depNm: e.target[0].value,
            leader: e.target[1].value,
            leaderPhone: e.target[2].value
        }

        try {
            const response = await fetch('http://localhost:8080/department/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            })
            const data = await response.json();
            if(data.status===0) {
                // alert("添加成")
                document.querySelector('.modal-mask').style.display = 'none'
                fetchData('query') // 刷新表格数据
            }
        } catch(err) {
            console.error('提交失败:', err)
        }
    })
    //表格函数
    // 新增以下功能函数

    async function disableCustomer(id, currentStatus) {

        let newStatus ='';
        let newre ='';
        if(currentStatus ===2){
            newStatus = 1;
            newre='启用合作';
        }else if(currentStatus ===1){
            newStatus = 2;
            newre='停止合作';
        }else{
            newStatus = 0;
            newre='发送审核';
        }
        try {
            const res = await fetch(`http://localhost:8080/sys/customerInfo/disable`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id, status: newStatus })
            });
            const data = await res.json();

            if(data.status === 0) {
                alert(`已${newre}`);
                fetchData('query');
            }else {
                alert("状态修改失败");
            }
        } catch(err) {
            console.error('状态修改失败:', err);
        }
    }
    // 修改功能弹窗
    let currentEditHandler = null;
    // 修改功能（需要实现编辑弹窗）
    function updateDepartment(item) {
        // 打开编辑弹窗
        // table-edit-btn
        const form = document.getElementById('modal-form-update');
        const modal = document.querySelector('#modal-mask-update'); // 需要创建编辑弹窗结构
        // 关闭旧监听器
        if (currentEditHandler) {
            form.removeEventListener('submit', currentEditHandler);
        }

        // 填充表单数据
        let depNm= document.querySelector('#edit-depNm').value = item.depNm;
        let leader=document.querySelector('#edit-leader').value = item.leader;
        let leaderPhone=document.querySelector('#edit-phone').value = item.leaderPhone;


        // 绑定提交事件
        // 定义新处理器
        currentEditHandler = async (e) => {
            e.preventDefault();
            const formData = {
                id: item.id,
                depNm: document.getElementById('edit-depNm').value ,
                leader: document.querySelector('#edit-leader').value,
                leaderPhone: document.querySelector('#edit-phone').value
            };

            try {
                const res = await fetch('http://localhost:8080/department/update', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(formData)
                });

                const data = await res.json();
                if(data.status === 0) {
                    modal.style.display = 'none';
                    fetchData('query');
                }else if (data.status === -1){
                    modal.style.display = 'none';
                }
            } catch(err) {
                console.error('更新失败:', err);
            }
        };
        form.addEventListener('submit', currentEditHandler);
        modal.style.display = 'flex';
    }

    async function showCustomerDetail(item) {
        const modal = document.getElementById('modal-mask-detail');
        try {
            const res = await fetch(`http://localhost:8080/sys/customerInfo/detail/${item.id}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            if (!res.ok) {
                throw new Error(`HTTP error! status: ${res.status}`);
            }

            const responseText = await res.text();
            let response;
            try {
                response = JSON.parse(responseText);
            } catch (parseError) {
                console.error('JSON解析错误:', parseError);
                throw new Error('服务器返回的数据格式不正确');
            }

            if (response.status === 0) {
                const data = response.data;
                
                // 更新UI
                document.getElementById('detail-customerName').textContent = data.customerName || '--';
                document.getElementById('detail-customerSimple').textContent = data.customerSimple || '--';
                document.getElementById('detail-typeName').textContent = data.typeName || '--';
                document.getElementById('detail-telephone').textContent = data.telephone || '--';
                document.getElementById('detail-mailbox').textContent = data.mailbox || '未填写';
                document.getElementById('detail-address').textContent = data.address || '未填写';
                document.getElementById('detail-status').textContent = 
                    data.status === 1 ? '合作中' : data.status === 2 ? '已退出' : '待审核';
                document.getElementById('detail-createTime').textContent = 
                    data.createTime ? formatDateTime(data.createTime) : '--';

                // 操作记录渲染
                const logsContainer = document.getElementById('detail-operationLogs');
                if (data.operateRecordList && data.operateRecordList.length > 0) {
                    logsContainer.innerHTML = data.operateRecordList.map(log => `
                        <div class="log-item">
                            <span>${log.createTime || '无时间'}</span>
                            <span class="log-type">${log.operateType}</span>
                        </div>
                    `).join('');
                } else {
                    logsContainer.innerHTML = '<div class="no-data">暂无操作记录</div>';
                }

                modal.style.display = 'flex';
            } else {
                alert('获取详情失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('详情加载失败:', err);
            alert(`加载失败: ${err.message}`);
        }
    }


    async function selectAllCustomer() {
        const response = await fetch('http://localhost:8080/sys/customerType/selectAllCustomerType', {
            method: 'GET',
            headers: {'Content-Type': 'application/json'}
        });

        const data = await response.json();

        if (data.status === 0) {
            fillSelectOptions('form-select-type', data.data, 'type_name');
            // fillSelectOptions('pc-role-select-update', data.data, 'role_nm');
        }
    }
    function fillSelectOptions(selectId, data, textKey) {
        const select = document.getElementById(selectId);
        while (select.options.length > 1) select.remove(1); // 保留默认选项
        data.forEach(item => {
            const option = document.createElement('option');
            option.value = item.id;
            option.textContent = item[textKey];
            select.appendChild(option);
        });
    }
    selectAllCustomer()

    // 修改按钮点击事件
    document.querySelectorAll('.table-edit-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const tr = btn.closest('tr');
            const id = tr.dataset.id;
            showUpdateModal(id);
        });
    });

    // 显示修改弹窗
    async function showUpdateModal(id) {
        const modal = document.getElementById('modal-mask-update');
        try {
            const res = await fetch(`http://localhost:8080/sys/customerInfo/detail/${id}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            if (!res.ok) {
                throw new Error(`HTTP error! status: ${res.status}`);
            }

            const response = await res.json();
            if (response.status === 0) {
                const data = response.data;
                
                // 填充表单数据
                document.getElementById('update-customerName').value = data.customerName || '';
                document.getElementById('update-customerSimple').value = data.customerSimple || '';
                document.getElementById('update-telephone').value = data.telephone || '';
                document.getElementById('update-mailbox').value = data.mailbox || '';
                document.getElementById('update-address').value = data.address || '';
                
                // 存储当前编辑的ID
                modal.dataset.currentId = id;
                modal.style.display = 'flex';
            } else {
                alert('获取详情失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('加载详情失败:', err);
            alert(`加载失败: ${err.message}`);
        }
    }

    // 修改表单提交
    document.getElementById('modal-form-update').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const modal = document.getElementById('modal-mask-update');
        const id = modal.dataset.currentId;
        
        const formData = {
            id: id,
            customerName: document.getElementById('update-customerName').value,
            customerSimple: document.getElementById('update-customerSimple').value,
            telephone: document.getElementById('update-telephone').value,
            mailbox: document.getElementById('update-mailbox').value,
            address: document.getElementById('update-address').value
        };

        try {
            const res = await fetch('http://localhost:8080/sys/customerInfo/update', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const response = await res.json();
            if (response.status === 0) {
                alert('修改成功');
                modal.style.display = 'none';
                fetchData('query'); // 刷新表格数据
            } else {
                alert('修改失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('提交失败:', err);
            alert('提交失败：' + err.message);
        }
    });

    // 导出按钮点击事件
    document.querySelector('.btn-export').addEventListener('click', async function() {
        // 构建查询参数
        const queryParams = {
            // 委托商名称：有值则添加，无值跳过
            ...(document.querySelector('input[placeholder="请输入委托商名称"]').value && {
                customerName: document.querySelector('input[placeholder="请输入委托商名称"]').value
            }),
            // 类型：有值则添加，无值跳过
            ...(document.querySelector('.form-select-type').value !== "" && {
                typeId: document.querySelector('.form-select-type').value
            }),
            // 状态：有值则添加，无值跳过
            ...(document.querySelector('.form-select-status').value !== "" && {
                status: document.querySelector('.form-select-status').value
            })
        };

        try {
            // 添加超时控制
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 15000); // 15秒超时

            // 将参数转换为查询字符串
            const queryString = new URLSearchParams(queryParams).toString();
            const response = await fetch(`http://localhost:8080/sys/customerInfo/export?${queryString}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                signal: controller.signal
            });

            clearTimeout(timeoutId);

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`导出失败: ${response.status} - ${errorText}`);
            }

            // 处理二进制流
            const blob = await response.blob();
            
            // 获取文件名
            const contentDisposition = response.headers.get('Content-Disposition');
            const filename = contentDisposition
                ? decodeURIComponent(contentDisposition.split('filename=')[1].replace(/"/g, ''))
                : `委托商信息列表_${new Date().toISOString().slice(0,10)}.xls`;

            // 创建下载链接（兼容IE）
            if (window.navigator.msSaveBlob) {
                // IE10+专用方法
                window.navigator.msSaveBlob(blob, filename);
            } else {
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = filename;
                link.style.display = 'none';

                document.body.appendChild(link);
                link.click();

                // 清理资源
                setTimeout(() => {
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);
                }, 100);
            }
        } catch (error) {
            console.error('导出失败:', error);
            if (error.name === 'AbortError') {
                alert('导出超时，请检查网络连接或联系管理员');
            } else {
                alert('导出失败：' + error.message);
            }
        }
    });
</script>
</body>
</html>